package org.snp

import com.sun.pdfview.PDFFile
import java.io._
import java.nio.channels.FileChannel
import javax.swing._
import java.awt.BorderLayout
import java.awt.event.ActionListener
import java.awt.event.ActionEvent
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.Toolkit

import org.slf4j.LoggerFactory

/**
 * A leafleting wizard. Idea is, slurp in a PDF and activate CSV,
 * and then poop out vast mailmerged PDF. Will be launched from java webstart.
 * As manipulating text in a PDF directly is flat out impossible, we must 
 * let the user select for us the areas where the address will do, then
 * calculate coordinates, add a new PDF layer, and put in the address.
 */
class Leafletomatic2 extends ComponentAdapter with ActionListener {
  private val GO = "GO"
  private val ADD = "ADD"
  private val log = LoggerFactory.getLogger(this.getClass);
  private val panel: BoxSelectPanel = new BoxSelectPanel()
  private var frame: JFrame = null
  private var viewport: JViewport = null
  //TODO rework when we do input file selector
  private val voters: Voters = new Voters(new File("src/test/resources/walklist.csv"))

  //show a pdf, simple prototype
  def showPdf() {
    //open a pdf, then try stamping some shit onto it
    //set up the frame and panel
    Toolkit.getDefaultToolkit().setDynamicLayout(false)
    //why does scrollpane completely fuck with resizing?
    val viewWindow = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    viewport = viewWindow.getViewport
    //panel.setPreferredSize(new Dimension(1000, 1000));
    frame = new JFrame("The SNP Surveyomatic");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    val toolBar = new JToolBar("PDF Toolbar")
    addButtons(toolBar)
    frame.add(viewWindow, BorderLayout.CENTER)
    frame.add(toolBar, BorderLayout.PAGE_START)
    frame.addComponentListener(this)
    frame.pack()
    frame.setVisible(true)

    //load a pdf from a byte buffer
    val file = new File("src/test/resources/Test_Survey.pdf")
    val raf = new RandomAccessFile(file, "r")
    val channel = raf.getChannel()
    val buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size())
    val pdffile = new PDFFile(buf)
    // show the first page
    val page = pdffile.getPage(0)
    panel.showPage(page)
  }

  //for now, we just want a go button
  private def addButtons(toolBar: JToolBar) {
    val goBtn: JButton = new JButton
    goBtn.setActionCommand(GO)
    goBtn.setToolTipText("Generate a merged PDF")
    goBtn.addActionListener(this)
    goBtn.setText("Go")
    toolBar.add(goBtn)

    val addBtn: JButton = new JButton
    addBtn.setActionCommand(ADD)
    addBtn.setToolTipText("Add a new address box")
    addBtn.addActionListener(this)
    addBtn.setText("+")
    toolBar.add(addBtn)
  }

  def actionPerformed(action: ActionEvent) {
    //go clicked!
    log.debug("Go clicked! Lets go..")
    val cmd = action.getActionCommand
    if (GO == cmd) {
      voters.generatePDF(panel.points)
    } else if (ADD == cmd) {
      log.info("+ clicked, need to add a new address box here, populated with sample data")
      panel.addBox(viewport.getViewPosition, voters.interleave(panel.points.size + 1))
    }
  }

  //frame resized, lets restrict ratio
  override def componentResized(evt: ComponentEvent) {
    var width: Float = evt.getComponent().getWidth()
    var height: Float = evt.getComponent().getHeight();

    panel.setAdjustedSize(height, width)
  }


}

object Leafletomatic {
  def main(args: Array[String]) = {
    //quick proof of concept
    var lft = new Leafletomatic2()
    lft.showPdf()
  }
}

